package com.ben.utils.receiver

import android.content.Context
import android.content.Intent
import android.content.IntentFilter

/**
 * Author: bin.yang
 * Maintainer: bin.yang
 * Date: 2020/4/21
 * Copyright: 2020 Inc. All rights reserved.
 * Desc:
 */
class HomeKeyReceiver(private val onHomeKeyListener: OnHomeKeyListener?) : BaseBroadcastReceiver() {

    interface OnHomeKeyListener {
        fun onClickHomeKey()
        fun onLongPressHomeKey()
    }

    override fun onReceive(context: Context, intent: Intent, action: String?) {
        if (action == Action) {
            val reason = intent.getStringExtra(SYSTEM_REASON)
            if (onHomeKeyListener != null) {
                when (reason) {
                    // 表示按了home键,程序到了home
                    SYSTEM_HOME_KEY -> {
                        onHomeKeyListener.onClickHomeKey()
                    }
                    // 表示长按home键,显示最近使用的程序列表
                    SYSTEM_HOME_KEY_LONG -> {
                        onHomeKeyListener.onLongPressHomeKey()
                    }
                }
            }
        }
    }

    override val intentAction: Array<String>
        get() = arrayOf(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)

    companion object {

        private const val SYSTEM_REASON = "reason"
        private const val SYSTEM_HOME_KEY = "homekey"
        private const val SYSTEM_HOME_KEY_LONG = "recentapps"
        private const val Action = Intent.ACTION_CLOSE_SYSTEM_DIALOGS
        fun register(context: Context, listener: OnHomeKeyListener?): HomeKeyReceiver {
            val receiver = HomeKeyReceiver(listener)
            context.registerReceiver(receiver, intentFilter)
            return receiver
        }

        val intentFilter: IntentFilter
            get() {
                val mIntentFilter = IntentFilter()
                mIntentFilter.addAction(Action)
                return mIntentFilter
            }
    }
}